package com.xiaolin.controller;

import com.xiaolin.pojo.AddFriends;
import com.xiaolin.pojo.Friends;
import com.xiaolin.pojo.User;
import com.xiaolin.pojo.vo.BaseResult;
import com.xiaolin.pojo.vo.WsMessage;
import com.xiaolin.service.AddFriendsService;
import com.xiaolin.service.FriendService;
import com.xiaolin.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @author XiaoLin
 * @date 2019/2/25 08:10
 */
@RestController
@RequestMapping("/friend")
public class FriendController {

    @Autowired
    private FriendService friendService;


    /**
     * 获取登陆用户的好友信息
     *
     * @param request
     * @return
     */
    @GetMapping("/findFriend")
    public ResponseEntity<BaseResult> findFriend(HttpServletRequest request) {
        try {
            //获取用户Id
            String userId = (String) request.getAttribute("userId");
            //查询用户好友信息
            List<Friends> friendsList = friendService.findFriendByMyId(userId);
            return ResponseEntity.ok(new BaseResult(0, "好友获取成功!", friendsList));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return ResponseEntity.ok(new BaseResult(1, "好友获取失败!"));
    }

    @Autowired
    private AddFriendsService addFriendsService;

    /**
     * Spring WebSocket消息发送模板
     */
    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    /**
     * 申请好友
     *
     * @param request
     * @param uid
     * @return
     */
    @PostMapping("/addFriends/{uid}")
    public ResponseEntity<BaseResult> addFriends(HttpServletRequest request, @PathVariable("uid") String uid) {
        try {
            //获取用户Id
            User user = (User) request.getAttribute("user");
            String userId = user.getUid();

            if (uid == null || userId.equals(uid)) {
                return ResponseEntity.ok(new BaseResult(1, "你不能申请自己为好友!"));
            }
            //判断是否已经是我的好友
            boolean b = friendService.findIsFriend(userId, uid);
            if (b) {
                return ResponseEntity.ok(new BaseResult(1, "对方已经是您的好友!"));
            }
            //判断是否已经存在请求信息
            boolean i = addFriendsService.findIsRequest(userId, uid);
            if (i) {
                return ResponseEntity.ok(new BaseResult(1, "好友已经在申请,请等待对方回应!"));
            }

            //创建请求对象
            AddFriends addFriends = new AddFriends();
            addFriends.setReceiveUid(uid);
            addFriends.setAddUid(userId);
            addFriends.setApplyDate(new Date());
            addFriends.setState(1);
            //保存好友信息
            addFriendsService.insert(addFriends);

            // 推送请求信息
            messagingTemplate.convertAndSendToUser(uid, "/queue/msg/new", new WsMessage(2, user.getNickName() + "正在申请加我为好友!"));

            return ResponseEntity.ok(new BaseResult(0, "好友申请发送成功!"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.ok(new BaseResult(1, "申请好友失败!"));
    }

    /**
     * 获取正在申请的记录
     *
     * @param request
     * @return
     */
    @GetMapping("/already")
    public ResponseEntity<BaseResult> alreadyFriends(HttpServletRequest request) {
        try {
            //获取用户Id
            String userId = (String) request.getAttribute("userId");
            //申请好友信息
            List<AddFriends> list = addFriendsService.findMyRequest(userId);
            return ResponseEntity.ok(new BaseResult(0, "获取成功!", list));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return ResponseEntity.ok(new BaseResult(1, "获取失败!"));
    }

    /**
     * 获取好友申请消息
     *
     * @param request
     * @return
     */
    @GetMapping("/getAddInfo")
    public ResponseEntity<BaseResult> getAddInfo(HttpServletRequest request) {
        try {
            //获取用户Id
            String userId = (String) request.getAttribute("userId");

            List<AddFriends> list = addFriendsService.findMyInfo(userId);
            return ResponseEntity.ok(new BaseResult(0, "获取成功!", list));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return ResponseEntity.ok(new BaseResult(1, "获取失败!"));
    }


    @Autowired
    private UserService userService;

    /**
     * 同意好友申请
     *
     * @param addfId
     * @return
     */
    @PutMapping("/infoAgree/{id}")
    public ResponseEntity<BaseResult> infoAgree(@PathVariable("id") Integer addfId, HttpServletRequest request) {
        try {
            //获取用户Id
            User user = (User) request.getAttribute("user");
            String userId = user.getUid();

            //获取申请信息
            AddFriends af = addFriendsService.findMyInfoById(addfId, userId);
            if (af == null) {
                ResponseEntity.ok(new BaseResult(1, "发送失败!"));
            }

            //生成好友关系信息
            Date date = new Date();
            Friends f1 = new Friends(af.getAddUid(), af.getReceiveUid(), date, "");
            Friends f2 = new Friends(af.getReceiveUid(), af.getAddUid(), date, "");

            //保存好友关系
            friendService.insert(f1);
            friendService.insert(f2);

            //修改申请信息为已
            addFriendsService.upState(af.getAddfId(), 0);

            //通知对方刷新好友列表
            messagingTemplate.convertAndSendToUser(af.getAddUid(), "/queue/msg/new", new WsMessage(3, user.getNickName() + "已经同意您的好友申请!"));

            return ResponseEntity.ok(new BaseResult(0, "好友已添加到您的好友列表!"));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return ResponseEntity.ok(new BaseResult(1, "发送失败!"));
    }

    /**
     * 忽略好友申请
     */
    @DeleteMapping("/infoIgnore/{id}")
    public ResponseEntity<BaseResult> infoIgnore(@PathVariable("id") Integer addfId, HttpServletRequest request) {
        try {
            //获取用户Id
            String userId = (String) request.getAttribute("userId");

            int i = addFriendsService.delete(addfId, userId);
            if (i <= 0) {
                return ResponseEntity.ok(new BaseResult(1, "请求失败!"));
            }
            return ResponseEntity.ok(new BaseResult(0, "忽略成功!"));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return ResponseEntity.ok(new BaseResult(1, "请求失败!"));
    }

}
